<template>
  <div class="page-content">
    <div class="d-flex justify-content-between align-items-center">
      <div v-if="view" class="w-100 text-right">
        <el-button size="small" class="mb-2 d-print-none" @click="handlePrint">
          <i class="fa fa-print"></i>
          打印
        </el-button>
      </div>
      <div class="text-danger h5" v-if="+this.relatedData.gua_letter_status === 3">
        本联担意向函已拒绝
      </div>
    </div>
    <div :id="printId" class="p-5 border-noprint">
      <div class="body-panel" v-loading="loading">
        <p class="body-text">
          {{ data.gua_org_name_short }}（联）函字
          <span class="text-decoration">[{{ data.letter_word_no || '-' }}]</span>
          第
          <span class="text-decoration">{{ data.letter_number_no || '-' }}</span>
          号
        </p>
        <h4 class="text-center mb-4">联担意向函</h4>
        <div class="mb-3">
          <span
            v-if="isUserTown || +this.relatedData.gua_letter_status !== 0 || view"
            class="text-decoration"
          >
            {{ data.submit_person_name || '-' }}
          </span>
          <c-select
            :options="agencies"
            v-else
            :props="{ value: 'client_id', label: 'org_name' }"
            v-model="orgId"
            style="width: 220px"
            @change="handleAgencySelect"
          ></c-select>
          ：
        </div>
        <!-- <span v-if="+relatedData.gua_letter_status === 3"
              class="body-span-text">
          就申请人<span class="text-decoration">{{replayName}}</span> 向
          <span class="text-decoration">{{relatedData.bank_name}}</span>
          申请人民币 <span class="text-decoration">{{total}}</span>、期限为
          <span class="text-decoration">{{year}}年</span> 的担保贷款业务事宜，
          我公司拟对申请人所申请的上述信贷融资业务及债务金额的
          {{data.bear_rate_divide}}%
          限提供担保；因{{data.bank_accept_option}}，无法对该项目进行
          <span class="text-decoration">联保/借用通道</span>的方式联保。
        </span> -->
        <span class="body-span-text">
          就申请人
          <span class="text-decoration">{{ replayName }}</span>
          向
          <span class="text-decoration">{{ relatedData.bank_name }}</span>
          申请人民币
          <span class="text-decoration">{{ total }}</span>
          、期限为
          <span class="text-decoration">{{ year }}年</span>
          的担保贷款业务事宜， 我公司拟对申请人所申请的上述信贷融资业务及债务金额的
          <template v-if="!view">
            <el-input
              v-model="data.bear_rate_divide"
              type="number"
              placeholder="请输入"
              style="width: 100px"
              class="m-0 p-0 input-td"
            ></el-input>
            %
          </template>
          <span v-else class="text-decoration">{{ data.bear_rate_divide }}%</span>
          限提供担保；现需对该项目按照
          <span class="text-decoration">联保/借用通道</span>
          方式进行联保， 贵公司将分担我公司应承担项目风险的
          <template v-if="!view">
            <el-input
              v-model="data.bear_rate"
              type="number"
              placeholder="请输入"
              style="width: 100px"
              class="m-0 p-0 input-td"
            ></el-input>
            %
          </template>
          <span v-else class="text-decoration">{{ data.bear_rate }}%</span>
          风险；担保费按照贷款金额的
          <span class="text-decoration">{{ relatedData.gua_rate || '-' }}%</span>
          核算，贵公司保费占比
          <template v-if="!view">
            <el-input
              v-model="data.gua_fee_rate"
              type="number"
              placeholder="请输入"
              style="width: 100px"
              class="m-0 p-0 input-td"
            ></el-input>
            %
          </template>
          <span v-else class="text-decoration">{{ data.gua_fee_rate }}%</span>
          ，由我公司收取后统一结算。
        </span>
        <p class="body-first-text">本函有效期为60日！</p>
        <div class="body-write">
          <p class="pt-5">
            {{ data.gua_company }}
          </p>
          <p>负责人或授权代理人(签字)：{{ data.gua_company_sign }}</p>
          <p class="bottm-time">
            <span v-if="view">{{ $utils.dateFormat(data.letter_date, 'yyyy-MM-dd') }}</span>
            <span v-else>{{ $utils.dateFormat(date, 'yyyy年MM月dd日') }}</span>
          </p>
        </div>
      </div>
    </div>
    <div class="text-center pt-2" v-if="!view">
      <el-button type="primary" style="min-width: 100px" v-if="isUserTown" @click="sendLetter(0)">
        申请联保
      </el-button>
      <div v-else>
        <el-button type="primary" style="min-width: 100px" @click="sendLetter(1)">
          确认联保
        </el-button>
        <!-- <el-button type="danger"
                   style="min-width: 100px"
                   @click="rejectLetter">拒绝联保
        </el-button> -->
      </div>
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { printA4, nzhToMoney } from '@vimi/utils-tool'

const date = new Date()

export default {
  components: {},
  props: {
    isView: Boolean,
    relatedData: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      date,
      loading: false,
      data: {},
      orgId: '',
      agencies: [],
      tableName: 'ele_letter_info',
    }
  },
  computed: {
    ...mapGetters(['user', 'org']),
    queryAddressCode() {
      return this.user.queryAddressCode || this.user.addressCode || this.org.addressCode
    },
    printId() {
      return `print-union-${this.relatedData.customer_related_id}`
    },
    orgRegionLever() {
      return this.user.orgRegionLever
    },
    isUserTown() {
      return this.user.orgRegionLever === 3
    },
    total() {
      const num =
        this.relatedData.res_funds ||
        this.relatedData.bank_approved_funds ||
        this.relatedData.apply_funds
      return nzhToMoney(num * 10000)
    },
    year() {
      const num = this.relatedData.approval_load_years || this.relatedData.load_years
      const text = nzhToMoney(num)
        .replace('元', '')
        .replace('整', '')
        .replace('角', '月')
        .replace('分', '')
      return text
    },
    view() {
      return this.isView || +this.relatedData.gua_letter_status === 3
    },
    replayName() {
      if (+this.relatedData.customer_type === 2) {
        return this.relatedData.corp_name || this.relatedData.corp_name
      } else {
        return `${this.relatedData.customer_name || this.relatedData.customer_name}（负责人：${
          this.relatedData.corp_name || this.relatedData.corp_name
        }）`
      }
    },
  },
  watch: {
    relatedData: {
      handler: function () {
        this.getData()
      },
      deep: true,
    },
  },
  created() {
    this.getAgency()
  },
  methods: {
    sendLetter(val) {
      if (!this.data.bear_rate_divide) {
        return this.$message.warning('请输入分险比列')
      }
      if (!this.data.bear_rate) {
        return this.$message.warning('请输入项目承担风险比列')
      }
      if (!this.data.gua_fee_rate) {
        return this.$message.warning('请输入保费占比')
      }
      this.data.customer_related_id = this.relatedData.customer_related_id
      this.data.letter_date = this.$utils.dateFormat(new Date(), 'yyyy-MM-dd')
      this.data.bank_name = this.relatedData.bank_name
      this.data.ele_letter_type = 2
      this.data.is_receipted = val
      this.$utils
        .msgbox({
          message: `确定发送此联保意向函?`,
          type: val > 1 ? 'error' : 'success',
          beforeClose: () => this.submit(),
        })
        .then(() => {
          this.$message.success('发送成功！')
          this.$emit('success', true)
        })
        .catch(() => this.$message.error(`发送失败，请重试！`))
    },
    rejectLetter() {
      this.data.is_receipted = 2
      this.$prompt('请输入拒绝理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: value => (!value ? '请输入拒绝理由' : true),
      })
        .then(({ value }) => {
          this.submit(value)
            .then(() => {
              this.$message.success('发送成功！')
              this.$emit('success', true)
            })
            .catch(() => this.$message.error(`发送失败，请重试！`))
        })
        .catch(err => err)
    },
    submit(value) {
      this.data.bank_accept_option = value
      if (this.data.ele_letter_info_id) {
        const data = {
          bank_accept_option: value,
          bank_name: this.relatedData.bank_name,
          letter_date: this.$utils.dateFormat(this.date, 'yyyy-MM-dd'),
          bear_rate_divide: this.data.bear_rate_divide,
          bear_rate: this.data.bear_rate,
          gua_fee_rate: this.data.gua_fee_rate,
          gua_org_name_short: this.data.gua_org_name_short,
          gua_org_code: this.data.gua_org_code,
          gua_company_sign: this.data.gua_company_sign,
          gua_company: this.data.gua_company,
          gua_org_id: this.data.gua_org_id,
          is_receipted: this.data.is_receipted,
          submit_person_name: this.data.submit_person_name,
        }
        if (!this.isUserTown) {
          data.bank_accept_date = this.$utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss')
        }
        return this.$api.updateData(
          this.$serviceName,
          this.tableName,
          this.data.ele_letter_info_id,
          data
        )
      } else {
        return this.$api.addData(this.$serviceName, this.tableName, this.data)
      }
    },
    handleAgencySelect(value) {
      const agency = this.agencies.find(item => item.client_id === value)
      this.$set(this.data, 'submit_person_name', agency.org_name)
    },
    getData() {
      const params = {
        'customer_related_id.eq': this.relatedData.customer_related_id,
        'ele_letter_type.eq': 2,
      }
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, params)
        .then(res => {
          this.data = (res && res.data && res.data[0]) || {}
          if (this.isUserTown) {
            this.$set(this.data, 'submit_person_name', this.org.orgName)
          } else {
            this.$set(this.data, 'gua_company', this.org.orgName)
            this.$set(this.data, 'gua_company_sign', this.org.realName)
            this.$set(this.data, 'gua_org_name_short', this.org.orgNameShort)
            this.$set(this.data, 'gua_org_id', this.org.clientId)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    async getAgency() {
      if (!this.queryAddressCode || this.isUserTown) {
        this.getData()
        return
      }
      const params = {
        address_code: this.queryAddressCode,
      }

      this.agencyLoading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, 'credit_select_view', params, {
          N1address_code: 'asc',
        })
      )
      this.agencyLoading = false

      const data = (res && res.data) || []
      this.agencies = data
      this.getData()
    },
    handlePrint() {
      printA4(
        document.getElementById(this.printId).innerHTML,
        `
        .vertical-align-middle td {vertical-align: middle;}
        .text-decoration {border-bottom: 1px solid;}
        .body-text {font-size: 1.2rem;}
        .body-first-text {font-size: 1.2rem;text-indent: 2rem;letter-spacing: 0.2rem;}
        .body-span-text {font-size: 1.2rem;margin-left: 2.8rem;letter-spacing: 0.2rem;}
        .body-write {text-align: right;}
      `
      )
    },
  },
}
</script>
<style lang="scss" scoped>
.page-content {
  max-width: 794px;
  margin: 0 auto;
  font-size: 1.2rem;
  line-height: 2;
}
.body-text {
  font-size: 1.2rem;
}
.body-first-text {
  font-size: 1.2rem;
  text-indent: 2.8rem;
  letter-spacing: 0.2rem;
}
.body-span-text {
  font-size: 1.2rem;
  margin-left: 2.8rem;
  letter-spacing: 0.2rem;
}
.text-decoration {
  border-bottom: 1px solid;
}
.body-write {
  text-align: right;
}
.border-noprint {
  border: 1px solid $border-color;
}
</style>
